﻿using System;
using System.Data;
using Epm.AppLogic.Framework; 
using System.Web;
using System.Web.SessionState;

namespace msBsc.Cls
{
    public class LookUPHandler : IHttpHandler,IRequiresSessionState
    {
        public LookUPHandler()
        {
        }

        private string GetFormParam(string ParamName)
        {
            if (string.IsNullOrEmpty(HttpContext.Current.Request.Params[ParamName]))
                return string.Empty;
            else
                return HttpContext.Current.Request.Params[ParamName];
        }

        public void ProcessRequest(HttpContext context)
        {
            doPageAjax(context);
        }

        private void doPageAjax(HttpContext context)
        { 
            try
            { 
                //UserInfo oUserInfo = new UserInfo();
                //if (!msBsc.SvRef.UserInfo.Online)
                //{
                //    msBcc.WebUi.BPlogin owtem = new msBcc.WebUi.BPlogin();
                //    owtem.SetLogin(null, false);
                //    if (!msBsc.SvRef.UserInfo.Online)
                //    {
                //        throw new Exception("错误：用户未登录！");
                //    }
                //}

                string strParamc = "", strVT = "", strSTYPE = "", strParamJson = "", strPostXml = "";
                if (!string.IsNullOrEmpty(context.Request.Params["q"]))
                    strParamc = context.Request.Params["q"].Replace("'", "");
                if (!string.IsNullOrEmpty(context.Request.Params["SVT"]))
                    strVT = context.Request.Params["SVT"];
                if (!string.IsNullOrEmpty(context.Request.Params["STYPE"]))
                    strSTYPE = context.Request.Params["STYPE"];
                if (!string.IsNullOrEmpty(context.Request.Params["JSPARAM"]))
                    strParamJson = context.Request.Params["JSPARAM"];
                if (!string.IsNullOrEmpty(context.Request.Params["POSTXML"]))
                    strPostXml = context.Request.Params["POSTXML"];
                msBsc.AppLogic.Cfg.SynDictionary htParam = gtJsonTo.GetHashData(strParamJson);

                //HttpServerUtility Server = HttpContext.Current.Server;
                //msBcc.AppLogic.Cfg.SynDictionary htParam = msBcc.AppLogic.Cfg.HttpTools.GetRowHash(Server.UrlDecode(strParamXml), null);
                //msBcc.AppLogic.Cfg.SynDictionary htPostData = msBcc.AppLogic.Cfg.HttpTools.GetRowHash(Server.UrlDecode(strPostXml), null);
                //strParamc = htParam["PPAGE"].ToString();
                string strJSon = "";
                CDbAccess DataObj = new CDbAccess();
                System.Data.DataSet ds = null;
                string strSql = "";

                string strColListJson = "";
                if (strSTYPE != string.Empty)
                {
                    object drConditon = null;// msBsc.SvRef.ApplicationConst.Const.dicSeekData[strSTYPE];
                    if (drConditon != null)
                    {
                        string strSqlTem1 = ((string[])drConditon)[0];


                        if (strSqlTem1 == string.Empty)
                        {
                            ds = DataObj.QueryBySQL("SELECT V_CDE='',V_NME=''");
                        }
                        else
                        {
                            CDbParmCollection parmCollection = new CDbParmCollection();

                            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("[@]{1}[a-z|A-Z]{1,}[a-z|A-Z|0-9|_]{0,}",
                                    System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                            System.Text.RegularExpressions.Match m = r.Match(strSqlTem1);
                            while (m.Success)
                            {
                                string strParamCde = m.Value.Substring(1).Trim();
                                if (parmCollection.IndexOf(strParamCde) == -1)
                                {
                                    if (strParamCde == "strUser")
                                    {
                                        parmCollection.Add(new CDbParm("strUser", ParameterDirection.Input, EDbType.String, 20, msBsc.SvRef.UserInfo.Operator));
                                    }
                                    //else if (strParamCde == "strOfce")
                                    //{
                                    //    parmCollection.Add(new CDbParm("strOfce", ParameterDirection.Input, EDbType.String, 20, Epm.AppLogic.Framework.ApplicationInfo.OperatorOffice));
                                    //}
                                    else if (strParamCde == "PAR")
                                    {
                                        parmCollection.Add(new CDbParm("PAR", ParameterDirection.Input, EDbType.String, 20, strParamc));
                                    }
                                    else
                                    {
                                        if (htParam != null && htParam[strParamCde] != null && htParam[strParamCde].ToString() != string.Empty)
                                        {
                                            parmCollection.Add(new CDbParm(strParamCde, ParameterDirection.Input, EDbType.String, 200, htParam[strParamCde].ToString()));
                                        }
                                        else if (context.Request.Params[strParamCde] != null)
                                        {
                                            parmCollection.Add(new CDbParm(strParamCde, ParameterDirection.Input, EDbType.String, 200, context.Request.Params[strParamCde]));
                                        }
                                        else
                                        {
                                            parmCollection.Add(new CDbParm(strParamCde, ParameterDirection.Input, EDbType.String, 200, ""));
                                        }
                                    }
                                }

                                m = m.NextMatch();
                            }
                            ds = DataObj.QueryBySQL(strSqlTem1, parmCollection);
                        }


                        //字段列表
                        strColListJson = GetGridOption(((string[])drConditon));
                        if (strColListJson != string.Empty)
                        {
                            strColListJson = "," + strColListJson;
                        }
                    }
                }
                if (ds != null)
                {
                    strJSon = msBsc.AppLogic.Cfg.HttpTools.GetJsonByTable(ds.Tables[0], "", 50, "");//构建的json数据
                    context.Response.Write("[" + strJSon + strColListJson + "]");
                }
                //strJSon = string.Format("'RetXmls':'{0}'", msBcc.AppLogic.Cfg.HttpTools.EzUrlEncode(msBcc.AppLogic.Cfg.HttpTools.EncoderXmlString(ds.Tables[0])).Replace("'", "\\'"));
                //Response.Write("[{");
                //Response.Write(strJSon);
                //Response.Write("}]");
            }
            catch (Exception err)
            {
                context.Response.Write("[{");
                context.Response.Write(string.Format("\"jmsg\":\"{0}\"", msBsc.AppLogic.Cfg.HttpTools.stringToJson(err.Message)));
                context.Response.Write("}]");

            }
        }

        private string GetGridOption(string[] drConditon)
        {
            string strJstem1 = "";
            //string strtem2=",{ id: '{0}', header: \"{1}\", width: {2} }";
            bool blHasCodeF = false;
            bool blHasNameF = false;
            string strFieldTem1 = drConditon[2];
            if (strFieldTem1 != string.Empty)
            {
                string[] arrtem1 = strFieldTem1.Split(new char[] { '\r', '\n' });
                foreach (string strFtem1 in arrtem1)
                {
                    if (!string.IsNullOrEmpty(strFtem1))
                    {
                        string strFcodetem = "";
                        string strFname = "";
                        string strFwidth = "100";
                        string strHidden = "false";
                        string[] arrFtem2 = strFtem1.Split(',');
                        for (int i = 0; i < arrFtem2.Length; i++)
                        {
                            if (i == 0)
                            {
                                strFcodetem = arrFtem2[i];
                            }
                            else if (i == 1)
                            {
                                strFname = arrFtem2[i];
                            }
                            else if (i == 2)
                            {
                                strFwidth = arrFtem2[i];
                            }
                            else if (i == 3 && arrFtem2[i] != string.Empty)
                            {
                                strHidden = arrFtem2[i].ToLower();
                            }
                        }
                        if (string.IsNullOrEmpty(strFcodetem))
                        {
                            continue;
                        }
                        else if (strFcodetem == "V_CDE")
                        {
                            blHasCodeF = true;
                        }
                        else if (strFcodetem == "V_NME")
                        {
                            blHasNameF = true;
                        }

                        if (strJstem1 != string.Empty)
                        {
                            strJstem1 += ",";
                        }
                        strJstem1 += "{ id: '" + strFcodetem + "', header: \"" + strFname + "\", width: " + strFwidth + ", hidden: " + strHidden + " }";
                    }
                }
            }
            if (!blHasCodeF)
            {
                strJstem1 += ",{ id: 'V_CDE', header: \"代码\", width: 100 }";
            }
            if (!blHasNameF)
            {
                strJstem1 += ",{ id: 'V_NME', header: \"名称\", width: 100 }";
            }
            if (strJstem1 != string.Empty)
            {
                strJstem1 = "[" + strJstem1 + "]";
            }
            return strJstem1;
        }


        public bool IsReusable
        {
            get { return true; }
        }
    }
}